package com.heima.user.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dtos.AppHttpCodeEnum;
import com.heima.common.dtos.ResponseResult;
import com.heima.common.exception.LeaNewsException;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.dtos.LoginDto;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.BCrypt;
import com.heima.utils.common.JwtUtils;
import com.heima.utils.common.RsaUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.Map;


/**
 * <p>
 * APP用户信息表 服务实现类
 * </p>
 *
 * @author itheima
 * @since 2023-01-11
 */
@Service
@Transactional
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {

    @Value("${leadnews.jwt.privateKeyPath}")
    private String privateKeyPath;

    @Value("${leadnews.jwt.expire}")
    private int expire;

    /**
     * @param loginDto
     * @return ResponseResult
     * 用户登入
     */
    @Override
    public ResponseResult login(LoginDto loginDto) {


        //用户登入
        //判断是否输入了手机号和密码
        if (StringUtils.isNotEmpty(loginDto.getPhone()) &&
                StringUtils.isNotEmpty(loginDto.getPassword())){

            //获取查询对象
            QueryWrapper<ApUser> queryWrapper = new QueryWrapper<>();
            QueryWrapper<ApUser> phone = queryWrapper.eq("phone", loginDto.getPhone());

            ApUser loginUser = getOne(phone);
            if (loginUser==null){
                System.err.println("用户不存在！！");
                //抛出自定义业务异常
                throw new LeaNewsException(AppHttpCodeEnum.PARAM_REQUIRE);
            }

            //判断该用户的密码是否正确
            boolean checkpw = BCrypt.checkpw(loginDto.getPassword(),loginUser.getPassword());
            if (checkpw==false){
                System.err.println("账号或者密码不正确！！");
                //抛出自定义业务异常
                throw new LeaNewsException(AppHttpCodeEnum.PARAM_INVALID);
            }

            //保护隐私数据
            loginUser.setPassword(null);
            //生成token
            try {
                PrivateKey privateKey = RsaUtils.getPrivateKey(privateKeyPath);
                String token = JwtUtils.generateTokenExpireInMinutes(loginUser, privateKey, expire);
                Map<String,Object> data = new HashMap<>();
                data.put("user",loginUser);
                data.put("token",token);

                //测试全局异常处理器的系统异常
                //data.put("exception",(1/0));

                System.err.println("用户登入成功！！");
                return ResponseResult.okResult(data);

            } catch (Exception e) {
                System.err.println("用户登入失败！！");
                throw new RuntimeException("用户登入失败");
            }

        }else {
            //游客登入
            //无需判断直接生成token返回
            try {
                ApUser visitUser = new ApUser();
                visitUser.setId(0);
                PrivateKey privateKey = RsaUtils.getPrivateKey(privateKeyPath);
                String token = JwtUtils.generateTokenExpireInMinutes(visitUser, privateKey, expire);
                Map<String,Object> data = new HashMap<>();
                data.put("user",visitUser);
                data.put("token",token);

                System.err.println("游客登入成功");
                return ResponseResult.okResult(data);

            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException("游客登入失败");
            }

        }
    }
}
